<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="被评分人" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入被评分人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['zxcrm:score:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zxcrm:score:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zxcrm:score:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['zxcrm:score:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scoreList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="状态" align="center" prop="scoreStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zxcrm_scope_status" :value="scope.row.scoreStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="当日评分" align="center" prop="dayScore" min-width="100px" >
        <template slot-scope="scope">
          <div style="position: relative;" v-if="scope.row.dayScore">
            <span>{{scope.row.dayScore}}分</span>
            &emsp;
             <span class="el-icon-view" style="color:#2C68FF;cursor: pointer;z-index: 9999;" @click="handleScoreDetail(scope.row)">查看原因</span>
             <div v-if="scoreDetailShow" style="position: fixed;width: 500px; box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);">
               <user-score-detail :list="scoreDetailList"   />
             </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="行为绩效得分" align="center" prop="behaviorPerformanceScore" />
      <el-table-column label="基础绩效分" align="center" prop="performanceBasedScore" />
      <el-table-column label="最后评分人" align="center" prop="lastScoreUserId" >
        <template slot-scope="scope">
          {{userMap[scope.row.lastScoreUserId]}}
        </template>
      </el-table-column>
      <el-table-column label="最后评分时间" align="center" prop="lastScoreTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastScoreTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAdd(scope.row)"
            v-hasPermi="['zxcrm:score:edit']"
            v-if="scope.row.userId != $store.state.user.id"
          >评分</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['zxcrm:score:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['zxcrm:score:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评分表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否合格" prop="qualified">
            <el-radio v-model="form.qualified" label="1" @change="handleQualified">合格</el-radio>
            <el-radio v-model="form.qualified" label="2">不合格</el-radio>
            <div v-if="form.qualified == 1"><span style="color: #999999;font-size: 10px;">注：评分合格可不选择评分原因，默认不扣除分数</span></div>
        </el-form-item>
        <el-form-item label="员工" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入员工" disabled />
        </el-form-item>
        <el-form-item label="评分原因" prop="evaluateIds" :rules="getEvaluateRules()">
          <el-select v-model="evaluateIdList" filterable collapse-tags multiple placeholder="请选择评分原因" class="w100" @change="handleEvaluateChange">
            <el-option
              v-for="item in  evaluateList"
              :key="item.id"
              :label="item.content"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" prop="otherScore" v-if="evaluateIdList.includes(60)" >
          <template slot-scope="scope">
            <el-input-number v-model="form.otherScore"  max="100" min="-100" size="small" ></el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="备注">
          <editor v-model="form.remark" :min-height="192"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScore, getScore, delScore, addScore, updateScore,listUserScore,score,listUserScoreByUserId } from "@/api/zxcrm/score"
import { listAllEvaluate} from "@/api/zxcrm/evaluate"
import { listAllUser} from "@/api/system/user"
import userScoreDetail from "@/views/zxcrm/components/userScoreDetail.vue"

export default {
  name: "Score",
  dicts: ['zxcrm_scope_status', 'zxcrm_qualified'],
  components:{userScoreDetail},
  data() {
    return {
      scoreDetailList:[],
      scoreDetailShow:false,
      userMap:[],
      evaluateIdList:[],
      evaluateList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评分表表格数据
      scoreList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        dayScore: null,
        behaviorPerformanceScore: null,
        performanceBasedScore: null,
        otherScore: null,
        lastScoreUserId: null,
        lastScoreTime: null,
        qualified: null,
        scoreStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        qualified:[
          {required:true,message:"是否合格为必填项",trigger:'blur'}
        ],
        otherScore:[
           {required:true,message:"分数为必填项",trigger:'blur'}
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getEvaluateList()
    this.getUserList()
  },
  watch:{
    evaluateIdList(newVal){
      if(evaluateIdList.includes(60)){
        this.$nextTick(()=>{
          this.$refs.form.clearValidate(['evaluateIds'])
        })
      }
    }
  },
  methods: {
    handleScoreDetail(row){
      listUserScoreByUserId(row.userId).then(res=>{
        this.scoreDetailList = res.data
      })
      this.scoreDetailShow = !this.scoreDetailShoww
    },
    handleQualified(e){
      this.form.otherScore = null
    },
    getUserList(){
      listAllUser().then(res=>{
        this.userMap = res.data.reduce((map,item)=>{
          map[item.userId] = item.nickName
          return map
        },{})
      })
    },
    getEvaluateRules(){
      return this.form.qualified == 2 ? [ { required: true, message: '评分原因为必填项', trigger: 'change' }] : []
    },
    handleEvaluateChange(e){
      if(e.includes(60)){
        this.evaluateIdList = [60]
        this.form.evaluateIds = null
      }else(
        this.form.evaluateIds = e.join(",")
      )

    },
    getEvaluateList(){
      listAllEvaluate().then(res=>{
        this.evaluateList = res.data
      })
    },
    /** 查询评分表列表 */
    getList() {
      this.loading = true
      listUserScore(this.queryParams).then(response => {
        this.scoreList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset(row) {
      this.evaluateIdList = []
      this.form = {
        id: null,
        userId: row.userId,
        userName: row.userName,
        dayScore: null,
        behaviorPerformanceScore: null,
        performanceBasedScore: null,
        otherScore: null,
        lastScoreUserId: null,
        lastScoreTime: null,
        qualified: '1',
        remark: null,
        scoreStatus: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset(row)
      this.open = true
      this.title = "添加评分表"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getScore(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改评分表"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateScore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            score(this.form).then(response => {
              this.$modal.msgSuccess("评价成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除评分表编号为"' + ids + '"的数据项？').then(function() {
        return delScore(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zxcrm/score/export', {
        ...this.queryParams
      }, `score_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style>
  .scoreDetail{
    
  }
</style>
